

using System.Collections.Generic;
namespace AFramework
{
    /// <summary>
    /// 链表对象池：存储相关对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class ListPool<T>
    {
        /// <summary>
        /// 栈对象：存储多个List
        /// </summary>
        static Stack<List<T>> m_ListStack = new Stack<List<T>>(8);

        /// <summary>
        /// 防止重复
        /// </summary>
        static HashSet<List<T>> m_ListHashSet = new HashSet<List<T>>();

        /// <summary>
        /// 出栈：获取某个List对象
        /// </summary>
        /// <returns></returns>
        public static List<T> Get()
        {
            if (m_ListStack.Count == 0)
            {
                return new List<T>(8);
            }
            var list = m_ListStack.Pop();
            m_ListHashSet.Remove(list);
            return list;
        }

        /// <summary>
        /// 入栈：将List对象添加到栈中
        /// </summary>
        /// <param name="toRelease"></param>
        public static void Release(List<T> toRelease)
        {
            toRelease.Clear();
            if (!m_ListHashSet.Contains(toRelease))
            {
                m_ListStack.Push(toRelease);
                m_ListHashSet.Add(toRelease);
            }
        }
    }

    /// <summary>
    /// 链表对象池 拓展方法类
    /// </summary>
    public static class ListPoolExtensions
    {
        /// <summary>
        /// 给List拓展 自身入栈 的方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="toRelease"></param>
        public static void Release2Pool<T>(this List<T> toRelease)
        {
            ListPool<T>.Release(toRelease);
        }
    }
}
